package servlet;

import com.alibaba.fastjson.JSON;
import dao.UserDao;
import dao.UserDaoImpl;
import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/testuname")
public class TestServlet extends HttpServlet {
    UserDao userDao = new UserDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数
        String username = req.getParameter("username");
        resp.setContentType("text/xml;charset=utf-8");
        User user = null;
        try {
            user = userDao.selectByUsername(username);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        PrintWriter writer = resp.getWriter();
        System.out.println("执行了后台检查");
        if (user != null){
           writer.print(JSON.toJSONString(user));
        }
    }

/*    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数
        String username = req.getParameter("username");
        resp.setContentType("text/xml;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        System.out.println("执行了后台检查");
        if ("admin".equals(username)){
            writer.println("账户已被注册");
        }else {
            writer.println("账户可用");
        }
    }*/

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        resp.setContentType("text/xml;charset=utf-8");
//        System.out.println(username);
        User user = null;
        try {
            user = userDao.selectByUsername(username);
//            System.out.println(user);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        String s = JSON.toJSONString(user);
//        System.out.println(s);
        PrintWriter writer = resp.getWriter();
        writer.print(s);

    }
}
